package org.jeecg.modules.ws.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.jeecg.modules.ws.entity.WsHbfxInterest;
import org.jeecg.modules.ws.entity.WsHblxDetail;
import org.jeecg.modules.ws.mapper.WsHblxDetailMapper;
import org.jeecg.modules.ws.service.IWsHbfxInterestService;
import org.jeecg.modules.ws.service.IWsHblxDetailService;
import org.jeecg.modules.ws.util.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * @Description: 付息详情
 * @Author: jeecg-boot
 * @Date: 2025-04-03
 * @Version: V1.0
 */
@Service
public class WsHblxDetailServiceImpl extends ServiceImpl<WsHblxDetailMapper, WsHblxDetail> implements IWsHblxDetailService {
    @Autowired
    private IWsHbfxInterestService interestService;
    @Autowired
    private ExcelUtil excelUtil;
    public List<String> getTitleList(List<WsHblxDetail> dataList){
        Set<String> setList = new HashSet<>();
        for (WsHblxDetail detail : dataList) {
            String bondCode = detail.getBondCode();
            String projectCode = detail.getProjectCode();
            List<WsHbfxInterest> interests = interestService.listByCode(bondCode, projectCode);
            for (WsHbfxInterest interest : interests) {
                setList.add(interest.getYear());
            }
        }
        // 将Set转换为List
        List<String> list = new ArrayList<>(setList);
        // 对List进行排序
        Collections.sort(list);
        return list;
    }

    public Map<String,Object> getTitleMap(List<WsHblxDetail> dataList){
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("发行年度","fxnd");
        map.put("发行月份","fxyf");
        map.put("到期年度","dqnd");
        map.put("项目名称","projectName");
        map.put("债券类型","bondType");
        map.put("发债类型","fzlx");
        map.put("到期日期","dqrq");
        map.put("年限","nx");
        map.put("提前还本","tqhb");
        map.put("利率","ll");
        map.put("发行日期","fxrq");
        map.put("本金","bj");
        map.put("年利息","nlx");
        map.put("总利息","zlx");
        map.put("本息合计","bxhj");
        List<String> list = getTitleList(dataList);
        for (String year : list) {
            map.put(year,year);
        }
        return map;
    }

    @Override
    public List<Map<String, Object>> packageRecords(List<WsHblxDetail> list) {
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (WsHblxDetail detail : list) {
            String bondCode = detail.getBondCode();
            String projectCode = detail.getProjectCode();
            Map<String, Object> detailMap = BeanUtil.beanToMap(detail);
            List<WsHbfxInterest> interests = interestService.listByCode(bondCode, projectCode);
            for (WsHbfxInterest interest : interests) {
                detailMap.put(interest.getYear(), interest.getInterest());
            }
            mapList.add(detailMap);
        }
        return mapList;
    }

    @Override
    public List<WsHblxDetail> listByBondCode(String bondCode) {
        LambdaQueryWrapper<WsHblxDetail> query = Wrappers.lambdaQuery(WsHblxDetail.class);
        query.eq(WsHblxDetail::getBondCode,bondCode);
        return list(query);
    }

    @Override
    public ModelAndView exportExcel(HttpServletRequest request, String bondCode) {
        LambdaQueryWrapper<WsHblxDetail> query = Wrappers.lambdaQuery(WsHblxDetail.class);
        query.eq(WsHblxDetail::getBondCode,bondCode);
        List<WsHblxDetail> list = list(query);
        Map sheetMap = excelUtil.customPackageSheet(packageRecords(list), "还本利息详情", getTitleMap(list));
        return excelUtil.exportXls(bondCode, Collections.singletonList(sheetMap));
    }

    public void exportExcel(HttpServletRequest request, HttpServletResponse response, String bondCode) {
        try {
            // 获取数据
            LambdaQueryWrapper<WsHblxDetail> query = Wrappers.lambdaQuery(WsHblxDetail.class);
            query.eq(WsHblxDetail::getBondCode, bondCode);
            List<WsHblxDetail> list = list(query);

            // 获取表头映射
            Map<String, Object> titleMap = getTitleMap(list);

            // 获取数据记录
            List<Map<String, Object>> records = packageRecords(list);

            // 创建ExcelWriter
            ExcelWriter writer = cn.hutool.poi.excel.ExcelUtil.getWriter();

            // 设置表头
            List<String> headers = new ArrayList<>();
            List<String> fields = new ArrayList<>();
            for (Map.Entry<String, Object> entry : titleMap.entrySet()) {
                headers.add(entry.getKey());
                fields.add(entry.getValue().toString());
            }

            // 写入表头
            writer.writeHeadRow(headers);

            // 写入数据
            for (Map<String, Object> record : records) {
                List<Object> row = new ArrayList<>();
                for (String field : fields) {
                    row.add(record.get(field));
                }
                writer.writeRow(row);
            }

            // 设置响应头
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            String fileName = URLEncoder.encode("还本利息详情_" + bondCode, "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

            // 输出到浏览器
            writer.flush(response.getOutputStream());
            writer.close();

        } catch (IOException e) {
            throw new RuntimeException("导出Excel失败", e);
        }
    }
}
